package chen.jia.xin.finalproject.ForegroundService;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import chen.jia.xin.finalproject.MainView.NotificationActivity;
import chen.jia.xin.finalproject.R;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyService extends Service {

    //私有变量
    private DownloadBinder downloadBinder = new DownloadBinder();
    //绑定活动与服务
    public class DownloadBinder extends Binder {
        public void startDownload(){
            Log.d("Service","Start Download");
        }
        public void stopDownload(){
            Log.d("Service","Stop Download");
        }
        public int getProgress(){
            return 0;
        }
    }

    public MyService() {
    }

    //转换JSON
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void getWeatherNoti(String weatherData) throws JSONException {
        //解析Json串得到今天的天气情况
        JSONObject jsonObjectALL = new JSONObject(weatherData);
        //获取到JSON数组数据
        String data = jsonObjectALL.getString("HeWeather6");
        JSONArray array = new JSONArray(data);
        //具体now天气数据(取出字符串再形成JSONObject)
        JSONObject allData = array.getJSONObject(0);
        JSONObject now = new JSONObject(allData.getString("now"));
        String temp = now.getString("tmp");
        String quality = now.getString("cond_txt");
        String tips = now.getString("wind_dir");
        String wind_sp = now.getString("wind_spd");

        Intent intent = new Intent(MyService.this,NotificationActivity.class);
        //注意这里是静态方法得到实例
        PendingIntent pendingIntent = PendingIntent.getActivity(MyService.this,0,intent,0);
        //创建通知管理者
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //创建通知通道(最新API方法)
        NotificationChannel notificationChannel = new NotificationChannel("1","channel",NotificationManager.IMPORTANCE_HIGH);
        //添加通道
        notificationManager.createNotificationChannel(notificationChannel);
        Notification notification = new NotificationCompat.Builder(this, "1")
                .setContentTitle("成都  " + temp + "度  " + quality)
                .setContentText("风向:  " + tips + "  风速 " + wind_sp+"级")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.weatherforcast)
                .setContentIntent(pendingIntent)
                .build();
        //开启前台服务和通知很类似
        startForeground(1,notification);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("Service","Service Create");
        //根据天气ID请求城市天气
        requestWeather("CN101270101");
    }

    //根据天气ID请求城市天气(和风天气平台)
    public void requestWeather(final String weatherId) {
        new Thread(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void run() {
                //城市ID与API_KEY结合URL
                String weatherUrl = "https://free-api.heweather.net/s6/weather/now?location="+weatherId+"&key=678828e88915434fbcb29bed68f878b4";
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(weatherUrl)
                            .build();
                    Response response = client.newCall(request).execute();
//                    BufferedReader reader = null;
//                    URL url = new URL("https://free-api.heweather.net/s6/weather/now?location="+weatherId+"&key=678828e88915434fbcb29bed68f878b4");
//                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//                    connection.setRequestMethod("GET");
//                    InputStream in = connection.getInputStream();
//                    reader = new BufferedReader(new InputStreamReader(in));
//                    StringBuilder response = new StringBuilder();
//                    String line;
//                    while ((line = reader.readLine()) != null) {
//                        response.append(line);
//                    }
                    String responseData = response.body().string();
                    getWeatherNoti(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //使用多线程技术避免在主线程中进行耗时操作
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("Service","Service onStartCommand");
                stopSelf();
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("Service","Service Destroy");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return downloadBinder;
    }
}
